import FileSaver from 'file-saver'

import { getStringLength } from 'src/util/utils'

const Excel = require('exceljs')

export function exportTableToExcel(tableColumn, tableData, fileName) {
  const workbook = new Excel.Workbook()
  // 2.创建表格，第二个参数可以配置创建什么样的工作表
  const worksheet = workbook.addWorksheet('Sheet1')

  // 3. 填充数据
  worksheet.columns = tableColumn.map(col => {
    return {
      header: col.title,
      key: col.dataIndex,
      // width: col.width
    };
  });
  tableData.forEach(row => {
    worksheet.addRow(row);
  });

  // 自动调整列宽
  worksheet.columns.forEach(function (column, columnNumber) {
    var maxLength = 0;
    column["eachCell"]({ includeEmpty: true }, function (cell, rowNumber) {
      const text = cell.value;
      var columnLength = text ? getStringLength(text) : 10;
      if (columnLength > maxLength) {
        maxLength = columnLength;
      }
    });
    maxLength += 1; // 宽度计算不准确,加一点空白
    column.width = maxLength < 10 ? 10 : maxLength;
  });

  // return
  // 4.写入 buffer
  const buffer = workbook.xlsx.writeBuffer().then(data => {
    // console.log('data', data)
    const blob = new Blob([data], {
      type: 'application/vnd.ms-excel;charset=utf-8'
    })
    console.log("导出成功！")
    FileSaver.saveAs(blob, `${fileName}.xlsx`)
  })
  return buffer
}